package m.base.action;

import m.base.model.UserInfo;
import m.base.service.StoreInfoService;
import m.base.service.UserInfoService;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.element.attr.TagColor;
import m.html.form.FormButton;
import m.html.form.FormEvent;
import m.html.form.FormInput;
import m.html.form.ModelForm;
import m.html.list.ListButton;
import m.html.list.ListColumn;
import m.html.list.ListElement;
import m.html.list.SuccessMethod;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;
import manage.model.AdminLogin;

import java.sql.SQLException;

@ActionMeta(name = "base/userInfo",title = "员工信息")
public class UserInfoAction extends BaseStatusAction{
    private UserInfo model;
    private void verifyUserNum() throws Exception {
        int userNum=getService(StoreInfoService.class).getStoreUserNum(PowerUtil.getSessionStoreOid());
        if(userNum>=LevelUtil.userNum()){
            throw new MException(this.getClass(),"用户数量已超过限制（当前商户级别限制用户数量："+LevelUtil.userNum()+"）");
        }
    }
    @RequestMeta(logTitle = "员工信息",logDescription = "保存员工信息",transaction = true)
    public JSONMessage doSave() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Store);//权限判断
        if(ObjectUtil.isEmptyOid(model)) verifyUserNum();
        getService(UserInfoService.class).save(model);
        getService(UserInfoService.class).setOperType(model.getOid(),model.getOrgGroup().getOid(),model.getOperType());
        CacheUtil.clear(UserInfo.class,model.getOid());
        return new JSONMessage(0,"保存成功");
    }
    /*
     * 编辑undefined
     */
    public VueResult toEdit() throws Exception {
        PowerUtil.verifyPower(PowerUtil.Store);//权限判断
        boolean add=false;
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*");
            model.setPassword("");
        }else{
            verifyUserNum();
            model=new UserInfo();
            add=true;
        }
        ModelForm form = new ModelForm("员工修改",2);
        form.addItem(
            FormInput.input("登录帐号", "model.username").setRequired(ObjectUtil.isEmptyOid(model)).setPlaceholder("请输入登录账号"),
            FormInput.input("登录密码", "model.password").setRequired(ObjectUtil.isEmptyOid(model)).setPlaceholder(add?"请输入登录密码":"不填则不会修改密码"),
            FormInput.input("真实姓名", "model.realname").setRequired(true).setPlaceholder("请输入真实姓名"),
            FormInput.input("联系电话", "model.phone").setRequired(true).setPlaceholder("请输入联系电话"),
            FormInput.checkBoxGroup("用户类型", "model.operType", "m.base.model.UserInfo!operType").setRequired(true).setSpan(2).setPlaceholder("请选择用户类型")
        )
        .addData("model",model)
        .addButton(
            FormButton.pri("保存","doSave")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
    }
    private ListColumn getOperTypeColumn(){
        return toElementColumn("用户类型","operType",260,
            ListElement.test("text.indexOf('"+UserInfo.OperType_Store+"')>=0",ListElement.tag("商户管理", TagColor.Red.toString(),false)),
            ListElement.test("text.indexOf('"+UserInfo.OperType_Stock+"')>=0",ListElement.tag("库存管理", TagColor.Blue.toString(),false)),
            ListElement.test("text.indexOf('"+UserInfo.OperType_Finance+"')>=0",ListElement.tag("财务管理", TagColor.Green.toString(),false)),
            ListElement.test("text.indexOf('"+UserInfo.OperType_Collect+"')>=0",ListElement.tag("统计汇总", TagColor.Purple.toString(),false))
        ).setDictType("m.base.model.UserInfo!operType").setFilter(true);
    }
    /*
     * 员工管理列表
     */
    public VueResult manageList() throws Exception {
        boolean power=PowerUtil.hasPower(PowerUtil.SysData);
        VueListResult result=getVueListResult("全部员工管理列表",UserInfo.class,actionUrl("manageList"));
        result.setFunction(true,false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("区域", "orgGroup.parent.name", 100, true));
        result.addCol(toTextColumn("商户", "orgGroup.name", 140, true));
        result.addCol(toTextColumn("真实姓名", "realname", 100, true));
        result.addCol(toTextColumn("联系电话", "phone", 100, true));
        result.addCol(toTextColumn("登录帐号", "username", 100, true));
        result.addCol(getOperTypeColumn());
        result.addCol(toDateColumn("创建时间", "createDate", 100, true));
        result.addCol(toDateTimeColumn("最后登录时间", "lastLoginTime", 130, true));
        result.addCol(toIntegerColumn("登陆次数", "loginCount", 100, true));
        result.addCol(toStatusColumn(power, true));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.not(QueryCondition.isEmpty("orgGroup.oid")));
        result.addCondition(QueryCondition.not(QueryCondition.eq("oid","1")));
        return result;
    }
    /*
     * 员工管理列表
     */
    public VueResult storeUserList() throws Exception {
        boolean power=PowerUtil.hasPower(PowerUtil.Store);
        VueListResult result=getVueListResult("员工管理列表",UserInfo.class,actionUrl("storeUserList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("真实姓名", "realname", 100, true));
        result.addCol(toTextColumn("联系电话", "phone", 100, true));
        result.addCol(toTextColumn("登录帐号", "username", 100, true));
        result.addCol(getOperTypeColumn());
        result.addCol(toDateColumn("创建时间", "createDate", 100, true));
        result.addCol(toDateTimeColumn("最后登录时间", "lastLoginTime", 130, true));
        result.addCol(toIntegerColumn("登陆次数", "loginCount", 100, true));
        result.addCol(toStatusColumn(power, true));
        result.addCol(toSpaceColumn("操作", 100,
            ListButton.modal("修改", ButtonType.PRIMARY,actionUrl("toEdit"),700, SuccessMethod.REFRESH)
                .addParam("model.oid","oid")
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.modal("新增", ButtonType.PRIMARY,actionUrl("toEdit"),700, SuccessMethod.REFRESH)
        );
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("orgGroup.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.not(QueryCondition.eq("oid","1")));
        return result;
    }
    /*
     * 员工列表
     */
    public VueResult viewStoreUserList() throws Exception {
        VueListResult result=getVueListResult("员工列表",UserInfo.class,actionUrl("viewStoreUserList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("真实姓名", "realname", 100, true));
        result.addCol(toTextColumn("联系电话", "phone", 100, true));
        result.addCol(toTextColumn("登录帐号", "username", 100, true));
        result.addCol(getOperTypeColumn());
        result.addCol(toDateColumn("创建时间", "createDate", 100, true));
        result.addCol(toDateTimeColumn("最后登录时间", "lastLoginTime", 130, true));
        result.addCol(toIntegerColumn("登陆次数", "loginCount", 100, true));
        result.addCol(toStatusColumn(false, true));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("orgGroup.oid", PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.not(QueryCondition.eq("oid","1")));
        return result;
    }

    @Override
    public void doRecoveryCallback() throws Exception {
        if(!PowerUtil.hasPower(PowerUtil.SysData)) {
            verifyUserNum();
            model = ModelQueryList.getModel(model, "*");
            PowerUtil.verifyStoreData(model.getOrgGroup().getOid());
        }
        CacheUtil.clear(UserInfo.class,model.getOid());
        CacheUtil.clear(AdminLogin.class,model.getOid());
    }

    @Override
    public void doDisableCallback() throws Exception {
        if(!PowerUtil.hasPower(PowerUtil.SysData)) {
            verifyUserNum();
            model = ModelQueryList.getModel(model, "*");
            PowerUtil.verifyStoreData(model.getOrgGroup().getOid());
        }
        CacheUtil.clear(UserInfo.class,model.getOid());
        CacheUtil.clear(AdminLogin.class,model.getOid());
    }

    @Override
    public UserInfo getModel() {
        return model;
    }

    @Override
    public String[] getStatusPower() {
        return new String[]{};
    }

    public void setModel(UserInfo model) {
        this.model = model;
    }
}
